# -*- coding:utf-8 -*-

'''
@文件    :snake.py
@说明    :
@时间    :2020/07/24 16:12:45
@作者    :小刘同学
@版本    :1.0
'''


# 测试pr
import os
import random
import sys

import pygame
import time 
from pygame.locals import *

import easygui as g
# 全局定义
SCREEN_X = 600
SCREEN_Y = 600

# 蛇类
# 点以25为单位
class Snake(object):
    # 初始化各种需要的属性 [开始时默认向右/身体块x5]
    def __init__(self):
        self.dirction = pygame.K_RIGHT
        self.body = []
        for x in range(5):
            self.addnode()

    # 无论何时 都在前端增加蛇块
    def addnode(self):
        left, top = (0, 0)
        if self.body:
            left, top = (self.body[0].left, self.body[0].top)
        node = pygame.Rect(left, top, 25, 25)
        if self.dirction == pygame.K_LEFT:
            node.left -= 25
        elif self.dirction == pygame.K_RIGHT:
            node.left += 25
        elif self.dirction == pygame.K_UP:
            node.top -= 25
        elif self.dirction == pygame.K_DOWN:
            node.top += 25
        elif self.dirction == pygame.K_s:
            node.top = top
            node.left = left
            #print(self.body)
        elif self.dirction == pygame.K_d:
            pass
             
        else :
            pass
        self.body.insert(0, node)

    # 删除最后一个块
    def delnode(self):
        self.body.pop()

    # 死亡判断
    def isdead(self,Stop):
        # K_d 开挂 1
        if Stop == pygame.K_d:
            global flag_wall
            flag_wall = 1
        if  Stop ==pygame.K_s :
            flag_wall = 0   
        if flag_wall == 1 :
            # 撞墙
            if self.body[0].x <  0:
                self.body[0].x = abs(self.body[0].x)
                self.body[0].x = self.body[0].x +550
            if self.body[0].y < 0 :
                self.body[0].y = abs(self.body[0].y)
                self.body[0].y = self.body[0].y + 550
            if self.body[0].x not in range(SCREEN_X):
               self.body[0].x = self.body[0].x -600
            if self.body[0].y not in range(SCREEN_Y):
                self.body[0].y = self.body[0].y -600
        else :
            if self.body[0].x  not in range(SCREEN_X):
                return True
            if self.body[0].y  not in range(SCREEN_Y):
                return True
            # 撞自己
            if self.body[0] in self.body[1:]:
                return True
        return False

    # 移动！
    def move(self):
        self.addnode()
        self.delnode()

    # 改变方向 但是左右、上下不能被逆向改变
    def changedirection(self, curkey):
        LR = [pygame.K_LEFT, pygame.K_RIGHT]
        UD = [pygame.K_UP, pygame.K_DOWN]
        Stop = [pygame.K_s,pygame.K_d]
        if curkey in LR+UD+Stop :
            if (curkey in LR) and (self.dirction in LR):
                return
            if (curkey in UD) and (self.dirction in UD):
                return
            self.dirction = curkey
        


# 食物类
# 方法： 放置/移除
# 点以25为单位
class Food:
    def __init__(self):
        self.rect = pygame.Rect(-25, 0, 25, 25)

    def remove(self):
        self.rect.x = -25

    def set(self):
        if self.rect.x == -25:
            allpos = []
            # 不靠墙太近 25 ~ SCREEN_X-25 之间
            for pos in range(25, SCREEN_X-25, 25):
                allpos.append(pos)
            self.rect.left = random.choice(allpos)
            self.rect.top = random.choice(allpos)
            #print(self.rect)


def show_text(screen, pos, text, color, font_bold=False, font_size=60, font_italic=False):
    # 获取系统字体，并设置文字大小
    cur_font = pygame.font.Font(font_path, font_size)
    # 设置是否加粗属性
    cur_font.set_bold(font_bold)
    # 设置是否斜体属性
    cur_font.set_italic(font_italic)
    # 设置文字内容
    text_fmt = cur_font.render(text, 1, color)
    # 绘制文字
    screen.blit(text_fmt, pos)

# 开始信息显示

def show_start_info(screen):
    
    font = pygame.font.Font(font_path, 30)
    tip = font.render('按任意键开始游戏', True, (65, 105, 225))
    gamestart = pygame.image.load(basepath+"/test.png")
    screen.blit(gamestart, (30, 30))
    screen.blit(tip, (240, 550))
    pygame.display.update()
    while True:  #键盘监听事件
        for event in pygame.event.get():  # event handling loop
            if event.type == QUIT:
                terminate()     #终止程序
            elif event.type == KEYDOWN:
                if (event.key == K_ESCAPE):  #终止程序
                    terminate() #终止程序
                else:
                    return #结束此函数, 开始游戏   


def main():
    pygame.init()
    screen_size = (SCREEN_X ,SCREEN_Y)
    screen = pygame.display.set_mode(screen_size)
    pygame.display.set_caption('贪吃蛇')
    show_start_info(screen)  
    clock = pygame.time.Clock()
    scores = 0
    isdead = False
    # 蛇/食物
    snake = Snake()
    food = Food()
    pygame.mixer.init()
    pygame.mixer.music.load(music_path + '天空之城.mp3')
    pygame.mixer.music.play(555)
    global key_flag
    key_flag = None
    global flag_wall
    flag_wall = 66
    global snake_color
    snake_color = (207, 255, 33)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                
                key_flag = event.key
                snake.changedirection(event.key)
                # 死后按space重新
                if event.key == pygame.K_SPACE and isdead:
                    return main()
        #渲染背景
        if flag_wall == 1:
            screen.fill((0, 0, 0))
            snake_color =(204, 59, 15)
        else:
            screen.fill((255, 255, 235))
        # 画蛇身 / 每一步+1分
        if not isdead:
            #scores+=1
            snake.move()

        for rect in snake.body:
            if snake.body.index(rect):
                pygame.draw.rect(
                    screen,snake_color , rect, 0)
            else:
                if snake.dirction == pygame.K_LEFT:
                 if not isdead:
                     snake_img = pygame.image.load(image_path + "head_left.png")
                elif snake.dirction == pygame.K_RIGHT:
                 if not isdead:
                     snake_img = pygame.image.load(image_path + "head_right.png")
                elif snake.dirction == pygame.K_UP:
                 if not isdead:
                     snake_img = pygame.image.load(image_path + "head.png")
                elif snake.dirction == pygame.K_DOWN:
                 if not isdead:
                     snake_img = pygame.image.load(image_path +"head_up.png")
                screen.blit(snake_img, rect)
        
            
        # 显示死亡文字
        isdead = snake.isdead(key_flag)
        if isdead:
            show_text(screen,(100,200),"You deed ",(227,29,18),False,30)
            show_text(screen,(150,260),'press space to try again...',(0,0,22),False,30)
            
        # 食物处理 / 吃到1分
        # 当食物rect与蛇头重合,吃掉 -> Snake增加一个Node
        if food.rect == snake.body[0]:
            scores+=1
            food.remove()
            snake.addnode()
        
        # 食物投递
        food.set()
        food_img = pygame.image.load(image_path + "/Basilisk.png")
        screen.blit(food_img,food.rect)
        #pygame.draw.rect(screen,(136,0,21),food.rect,0)
        
        # 显示分数文字
        show_text(screen,(50,500),'Scores: '+str(scores),(223,223,223))
        
        pygame.display.update()
        # 延时
        clock.tick(5)
    
    
if __name__ == '__main__':
    basepath = os.path.dirname(__file__)  # 当前文件所在路径
    # 音乐
    music_path = str(basepath) + "/source/music/"
    font_path = str(basepath) + "/source/font/simhei.ttf"
    image_path = str(basepath) + "/source/image/"
    main()
